package initialize

import (
	"fmt"
	"order_srv/global"

	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

func InitRegisterConsul() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%s", global.ServerConfig.ConsulConfig.ConsulHost, global.ServerConfig.ConsulConfig.ConsulPort)
	//实例化consul客户端
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Panic(err)
	}

	//生成健康检测的检查对象
	check := &api.AgentServiceCheck{
		Interval:                       "2s", //健康检查间隔
		GRPC:                           fmt.Sprintf("%s:%d", global.ServerConfig.Ip, global.ServerConfig.Port),
		Timeout:                        "5s",
		DeregisterCriticalServiceAfter: "1s",
	}

	//注册服务
	registration := new(api.AgentServiceRegistration)
	registration.Name = global.ServerConfig.Name
	registration.ID = global.ServerId
	registration.Address = global.ServerConfig.Ip
	registration.Port = global.ServerConfig.Port
	registration.Tags = global.ServerConfig.ConsulConfig.Tags
	registration.Check = check

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		zap.S().Panic(err)
	}
}
